var DBAccess = require('./db');
require('./../models/secretario.model');

function SecretarioDAO() {
    var db = DBAccess.getInstance();
    var model = db.model('Secretario');

    this.add = function(secretario, callback) {
        db.connect();
        if (arguments.length === 2 && typeof arguments[1] == 'function') {
            secretario.save(function(err) {
                if (err) throw err;
                callback();
            });
        }
        else {
            secretario.save(function(err) {
                if (err) throw err;
            });
        }
    }

    this.remove = function(secretario) {
        db.connect();
        model.remove({ username : secretario.username}, function(err) {
            if (err) throw err;
        });
    }

    this.get = function(secretario, callback) {
        db.connect();
        model.findOne({ username : secretario.username}, function(err, data) {
            if (!data) throw new Error('Not found!');
            callback(err, data);
        });
    }

    this.update = function(id, update) {
        db.connect();
        model.findOne({ username: id}, function(err, old) {
            if(!old)
                throw new Error('Secretario not found!');
            old.nome = update.nome || old.nome;
            old.email = update.nome || old.nome;
            old.username = update.username || old.username;
            old.matricula = update.matricula || old.matricula;
            old.telefone = update.telefone || old.telefone;
            old.roles = update.roles || old.roles;
            old.save(function(err) {
                if(err) throw err;
            });
        });
    }

    this.getAll = function(callback) {
        db.connect();
        if(typeof callback != 'function')
            throw new Error('Give me a callback function!');
        model.find({}, function(err, all) {
            callback(err, all);
        });
    }

    this.getModel = function() {
        return new model();
    }

}

module.exports = SecretarioDAO;
